package com.squirrel.common.exception;

import com.squirrel.common.response.ResponseResult;
import com.squirrel.common.response.ResponseResultUtils;
import com.squirrel.common.response.code.IEnum;
import io.jsonwebtoken.JwtException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Description GlobalExceptionHandler 全局异常处理类
 * @Author 关远键
 * @Version v1.0.0
 * @Date 2021/11/9 14:28
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 拦截所有异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = {Exception.class})
    public ResponseResult requestException(Exception e) {
        e.printStackTrace();
        if (e instanceof IException) {
            return error(e);
        }

        return ResponseResultUtils.error("未知错误");
    }

    public ResponseResult error(Exception e) {
        IException iException = (IException) e;
        IEnum iEnum = iException.getIEnum();
        ResponseResult<Object> errorResult = ResponseResultUtils.error(iEnum);
        return errorResult;
    }

    @ExceptionHandler(MyAuthenticationException.class)
    public ResponseResult handleJwtException(MyAuthenticationException e) {
        return ResponseResultUtils.error(e.getIEnum());
    }
}
